package Deom1.DBUtils;

import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    //数据源
    private static MysqlDataSource dataSource=null;
    //数据库连接串
    private  static  final String URL="jdbc:mysql://127.0.0.1:3306/exam?characterEncoding=utf8"
            +"&allowPublicKeyRetrieval=true&useSSL=false";
    //用户名
private static final String USER="root";
//密码
private static final String POSSWORD="123456";
//数据库连接，登录账号密码
static {
  MysqlDataSource mysqlDataSource=new MysqlDataSource();
  mysqlDataSource.setURL(URL);
  mysqlDataSource.setUser(USER);
  mysqlDataSource.setPassword(POSSWORD);
  dataSource=mysqlDataSource;
}

//私有化构造方法
private DBUtil(){}

public static Connection getConnection(){
    try {
        return dataSource.getConnection();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

public static void close(ResultSet resultSet, Statement statement,Connection connection){
    if (resultSet!=null){
        try {
            resultSet.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    if (statement!=null){
        try {
            statement.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    if (connection!=null){
        try {
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
}
